import $ from '../jquery/jquery.min.js';
import ajax from '../utils/ajax'



const searchObj = {
    value: '',
    currentPage: 1,
    pageSize: 5,
    pages: 0,
    total: 0
}


showCasaData();
showPageData();

//打开房屋租赁合同
$('#houseRent').on('click', '.show-casa-modal', function () {
    $('#add-casa-contract-modalbox').show();
    if ($(this).text() == '编辑') {
        //获取选择要修改用户的数据渲染到模态框
        const _id = $(this).data('id');
        $('#house-title-h4').addClass('gai');
        $('#house-title-h4').attr('data-id', _id);
        getCasaDatasById(_id);
    }else{
        $('#house-title-h4').removeClass('gai');
        showCommunityCasa();
    }
});



//关闭房屋租赁合同
$('#casa-return-btn').click(function () {
    $('#add-casa-contract-modalbox').hide();
    clearData();
});




//新增合同||||||||修改合同
$('#casa-save-contract-btn').click(function () {
    //获取当前输入框的值
    const communityId = $('#casa-choose-plot').val();
    const houseNumber = $('#casaNumber-select').val();
    const size = $('#casa-size').val();  // 租金方式
    const price = $('#casa-price').val(); //租金
    const locations = $('#casa-locations').val(); //朝向
    const leasee = $('#casa-leasee').val(); 
    const leaseeContacts = $('#casa-leaseeContacts').val();
    const leaseeTel = $('#casa-leaseeTel').val();
    const contractNumber = $('#casa-contractNumber').val();
    const tenant = $('#casa-tenant').val();
    const signingDate = $('#casa-signingDate').val();
    const representative = $('#casa-representative').val();
    const tenantContacts = $('#casa-tenantContacts').val();
    const contractType = $('#casa-contractType').val();
    const term = $('#casa-term').val();
    const off_hire = $('#casa-off_hire').val();
    const start_date = $('#casa-start_date').val();
    const area = $('#casa-area').val();
    const earnestMoney = $('#casa-earnestMoney').val();
    const agencyfee = $('#casa-agencyfee').val();
    const isRentMoney = $('#casa-isRentMoney').prop('checked');
    const totalMoney = $('#casa-isRentMoney').prop('checked') ? $('#casa-totalMoney').val() : 0;
    const increase = $('#casa-increase').val();
    const earnestExplain = $('#casa-earnestExplain').val();
    const remark = $('#casa-remark').val();
    const accessory = $('#casa-accessory-btn').attr('src');
    const contractName='房屋租赁合同';
    if(price!=''&&leasee!=''&&leaseeContacts!=''&&leaseeTel!=''&&size!=''&&locations!=''){
        if($('#house-title-h4').prop('class')=='gai'){
            //编辑
            const _id = $('#house-title-h4').data('id');
            ajax({
                url: '/house',
                type: "PUT",
                data: {
                    _id,
                    communityId,
                    houseNumber,
                    price,
                    leasee,
                    leaseeContacts,
                    leaseeTel,
                    size,
                    locations,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory
                },
                success(res) {
                    if (res.code == 200) {
                        alert("修改合同成功");
                        $('#add-casa-contract-modalbox').hide();
                       showCasaData();
                        clearData();
                    } else {
                        alert("修改合同失败");
                        $('#add-casa-contract-modalbox').hide();
                        clearData();
                    }
                }
            });
        }else{
            //新增
            ajax({
                url: '/house',
                type: "POST",
                data: {
                    communityId,
                    houseNumber,
                    price,
                    leasee,
                    leaseeContacts,
                    leaseeTel,
                    size,
                    locations,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory,
                    contractName
                },
                success(res) {
                    if (res.code == 200) {
                        alert("新增合同成功");
                        const objs = {
                            houseId: res.data._id,
                            numbers: res.data.houseNumber, //资源名称
                            leaseeContacts: res.data.leaseeContacts,//联系人
                            contractNumber: res.data.contractNumber,//合同编号
                            contractName,
                            price:res.data.price,//收费金额  2
                            leaseeTel:res.data.leaseeTel,//联系电话   2
                            tenant:res.data.tenant, //租户  2
                            signingDate:res.data.signingDate,//签订日期  2
                            off_hire:res.data.off_hire,//停租日期   2
                            start_date:res.data.start_date,//起租日期`  2
                        }
                        addContracts(objs);
                        $('#add-casa-contract-modalbox').hide();
                        if ($('#houseRent-tb tbody tr').length == searchObj.pageSize) {
                            showPageData();
                        }
                        showCasaData();
                        clearData();
                    } else {
                        alert("新增合同失败");
                        $('#add-casa-contract-modalbox').hide();
                        clearData();
                    }
                }
            });
        
        }
    }else{
        alert('输入框都不能为空!')
    }
});




//清除模态框数据
function clearData(){
    $('#casa-size').val('');
    $('#casa-price').val('');
    $('#casa-locations').val('');
    $('#casa-leasee').val('');
    $('#casa-leaseeContacts').val('');
    $('#casa-leaseeTel').val('');
    $('#casa-contractNumber').val('');
    $('#casa-tenant').val('');
    $('#casa-signingDate').val('');
    $('#casa-representative').val('');
    $('#casa-tenantContacts').val('');
    $('#casa-contractType').val('');
    $('#casa-term').val('');
    $('#casa-off_hire').val('');
    $('#casa-start_date').val('');
    $('#casa-area').val('');
    $('#casa-earnestMoney').val('');
    $('#casa-agencyfee').val('');
    $('#casa-isRentMoney').prop('checked',false);
    $('#casa-totalMoney').val('');
    $('#casa-increase').val('');
    $('#casa-earnestExplain').val('');
    $('#casa-remark').val('');
}





//渲染小区
function showCommunityCasa() {
    ajax({
        url: '/community',
        type: "GET",
        data: { value: '' },
        success(res) {
            if (res.code == 200) {
                //设置小区选择
                $('#casa-choose-plot').html(res.result.map(item => `<option value=${item._id}>${item.communityName}</option>`).join(''));
            }
        }
    })
}


//渲染指定小区
function showCommunityCasaById(_id) {
    ajax({
        url: '/community',
        type: "GET",
        data: { value: '' },
        success(res) {
            if (res.code == 200) {
                $('#casa-choose-plot').html(res.result.map(item => `<option value=${item._id}>${item.communityName}</option>`).join(''));
                $('#casa-choose-plot').val(_id);
            }
        }
    })
}






//渲染房屋租赁合同数据
function showCasaData() {
    ajax({
        url: "/house",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                searchObj.pages = res.pages;
                searchObj.total = res.total;
                renderCasadata(res.result);
            }
        }
    })
}

function renderCasadata(data) {
    $('#houseRent-tb tbody').html(data.map(item => `<tr>
    <td>${item.communityId.communityName}</td>
    <td>${item.houseNumber}</td>
    <td>${item.area}m²</td>
    <td>${item.locations}</td>
    <td>${item.leasee}</td>
    <td>${item.leaseeContacts}</td>
    <td>${item.leaseeTel}</td>
    <td>${item.price}</td>
    <td>${item.start_date}</td>
    <td>${item.size}</td>
    <td><span data-id=${item._id} class='casa-detail-btn' >详情</span><span class='show-casa-modal' data-id=${item._id}>编辑</span><span data-id=${item._id} class='del-casa-btn'>删除</span></td>
</tr>`).join(''));
}



//获取当前日期
function getDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = parseInt(date.getMonth()) + 1;
    const day = date.getDate();
    return `${year}-0${month}-${day}`;
}




//判断合同状态
function getType(data1, data2, data3) {
    const date1 = new Date(data1);
    const date2 = new Date(data2);
    const date3 = new Date(data3);
    if (date2 >= date1 && date2 <= date3) {
        return true;
    } else {
        return false;
    }
}





//点击删除按钮，删除对应客户数据
$('#houseRent-tb tbody').on('click', '.del-casa-btn', function () {
    const _id = $(this).data('id');
    delCasaData(_id);
});


//删除客户数据
function delCasaData(_id) {
    ajax({
        url: '/house',
        data: { _id },
        type: "DELETE",
        success(res) {
            if (res.code == 200) {
                // 删除成功
                if ((searchObj.total) % (searchObj.pageSize) == 1) {
                    $('#houseRent-tb tbody tr').length == 1 ? searchObj.currentPage-- : searchObj.currentPage;
                    showPageData();
                }
                showCasaData();
            } else {
                alert('抱歉,删除失败');
            }
        }
    })
}





// 渲染页码相关div
function showPageData() {
    ajax({
        url: "/house",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                renderPageData(Number(res.pages));
            } 
        }
    })
}

function renderPageData(pages) {
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<span>${i}</span>`;
    }
    $('#houseRent-bottom-choose-page-div .add-pages-span').html(html);
    $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#houseRent-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
}




//点击切换页面
$('#houseRent-bottom-choose-page-div .add-pages-span').on('click', 'span', function () {
    $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(this).addClass('active');
    const currentPage = $(this).text();
    searchObj.currentPage = Number(currentPage);
   showCasaData();
});

//点击切换页面显示条数
$('#casa-pageSize-select').change(function () {
    const pageSize = $('#casa-pageSize-select').val();
    searchObj.pageSize = Number(pageSize);
    searchObj.currentPage = 1;
    showCasaData();
    showPageData();
});


//跳至X页事件
$('#casa-go-page').keyup(function (e) {
    if (e.keyCode == 13) {
        const page = $('#casa-go-page').val();
        if (page != '' && typeof Number(page) == 'number' && !isNaN(Number(page))) {
            if (Number(page) < 1) {
                searchObj.currentPage = 1;
               showCasaData();
                $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#houseRent-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else if (Number(page) > searchObj.pages) {
                searchObj.currentPage = searchObj.pages;
               showCasaData();
                $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#houseRent-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else {
                searchObj.currentPage = Number(page);
               showCasaData();
                $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#houseRent-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            }
        }
    }
});


//上一页，下一页事件
$('#casa-prev-span').click(function () {
    if (searchObj.currentPage <= 1) {
        searchObj.currentPage = 1;
    } else {
        searchObj.currentPage--;
    }
    showCasaData();
    $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#houseRent-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


$('#casa-next-span').click(function () {
    if (searchObj.currentPage == searchObj.pages) {
        searchObj.currentPage = searchObj.pages;
    } else {
        searchObj.currentPage++;
    }
    showCasaData();
    $('#houseRent-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#houseRent-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


//点击搜索按钮查询
$('#search-houseRent-btn').click(function () {
    const value = $('#search-casa').val();
    searchObj.value = value;
    searchObj.currentPage = 1;
    showCasaData();
    showPageData();
});






//通过id查询对应的房屋详细合同资料
function getCasaDatasById(_id) {
    ajax({
        url: '/house/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                showCommunityCasaById(res.result.communityId._id);
                $('#casaNumber-select').val(res.result.houseNumber);
                $('#casa-size').val(res.result.size);
                $('#casa-price').val(res.result.price);
                $('#casa-locations').val(res.result.locations);
                $('#casa-leasee').val(res.result.leasee);
                $('#casa-leaseeContacts').val(res.result.leaseeContacts);
                $('#casa-leaseeTel').val(res.result.leaseeTel);
                $('#casa-contractNumber').val(res.result.contractNumber);
                $('#casa-tenant').val(res.result.tenant);
                $('#casa-signingDate').val(res.result.signingDate);
                $('#casa-representative').val(res.result.representative);
                $('#casa-tenantContacts').val(res.result.tenantContacts);
                $('#casa-contractType').val(res.result.contractType);
                $('#casa-term').val(res.result.term);
                $('#casa-off_hire').val(res.result.off_hire);
                $('#casa-start_date').val(res.result.start_date);
                $('#casa-area').val(res.result.area);
                $('#casa-earnestMoney').val(res.result.earnestMoney);
                $('#casa-agencyfee').val(res.result.agencyfee);
                $('#casa-isRentMoney').prop('checked',res.result.isRentMoney);
                $('#casa-totalMoney').val(res.result.totalMoney);
                $('#casa-increase').val(res.result.increase);
                $('#casa-earnestExplain').val(res.result.earnestExplain);
                $('#casa-remark').val(res.result.remark);
                $('#casa-accessory-btn').attr('src',res.result.accessory);
            } 
        }
    })
}






//上传图片
$('#file-input-casa').change(function (e) {
    const files = e.target.files;
    const fd = new FormData();
    fd.append('file', files[0]);
    $.ajax({
        url: 'http://localhost:3100/house/uploadImages',
        type: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success(res) {
            if (res.code == 200) {
                $('#casa-accessory-btn').attr('src', 'http://localhost:3100/' + res.data);
            }
        }
    });
});




//点击详情查询合同图片
$('#houseRent-tb tbody').on('click', '.casa-detail-btn', function () {
    const _id = $(this).data('id');
    getCasaById(_id);
});



//通过id查询对应的房屋租赁合同图片数据
function getCasaById(_id) {
    ajax({
        url: '/house/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                $('#show-img-div').show();
                $('#cancle-img').attr('src', res.result.accessory);
            } 
        }
    })
}





//添加数据到合同管理集合
function addContracts(obj){
    ajax({
        url:'/contracts',
        type:'POST',
        data:obj,
        success(res){
        }
    });
}
